import React, { Component } from 'react';
import { connect } from 'dva';

import { Form, Input, Button, notification, Col, Row, message, Cascader } from 'antd';
import { UmiComponentProps, FormComponentProps } from '@/common/type';

import { DICT } from '../enum'

// import PointSelect from '@/components/PointSelect';
import { DividerItem } from '@/components/DividerItem';
// import { MyIcon } from '@/components/MyIcon';
// import { DropDownSelectObj } from '@/components/DropDownSelect';

import TrimInput, { withTrim } from '@/components/TrimInput'
// import { MyButton } from '@/styled/form';
import { fomatter } from '@/utils/formatter';

const TextArea = withTrim(Input.TextArea);

interface P {
  data?: {
    id?: string;
    floorPlanX: string; floorPlanY: string;
    brandId?: string; productId?: string;
    brandName?: string; productName?: string;
    buildId?: string; floorId?: string; areaId?: string;
    buildName?: string; floorName?: string; areaName?: string;
  },
  location?: Array<any>;
  brand?: Array<any>;
  dict?: any;
  image?: string;
  lLocation?: boolean;
  lBrand?: boolean;
}
type Props = P & UmiComponentProps & FormComponentProps;

@connect(({ device_general, loading }) => ({
  dict: device_general.dict || {},
  location: device_general.location || [],
  brand: device_general.brand || [],
  image: device_general.image,
  lLocation: loading.effects['device_general/queryLocation'],
  lBrand: loading.effects['device_general/queryBrand']
}))
class FormItem extends Component<Props, any> {
  state = {
    show: false,
    tmpLocation: null
  };

  componentDidMount() {
    const { data, form, dispatch } = this.props;

    dispatch({
      type: 'device_general/init', payload: {
        dict: { keyList: DICT },
      }
    })
    if (data) {
      const {
        // floorPlanX, floorPlanY,
        brandId, productId,
        brandName, productName,
        buildId, floorId, areaId,
        buildName, floorName, areaName,
        ...res
      } = data;

      form.setFieldsValue({
        // location: floorPlanX && floorPlanY ? `${floorPlanX},${floorPlanY}` : null,
        // brandList: [brandId, productId],
        // buildList: [buildId, floorId, areaId],
        ...res,
        // fire: '700190022'
      })
    } else {
      // form.setFieldsValue({
      //   fire: '700190022'
      // })
    }
  }

  handleMap = () => {
    const { dispatch, form, data } = this.props;
    const { getFieldValue } = form;

    const list = getFieldValue('buildList');
    if ((!Array.isArray(list) || !list[1]) && !data.floorId) {
      message.warn('请选择楼层');
      return;
    }

    dispatch({
      type: 'device_general/queryFloorImg',
      payload: Array.isArray(list) && list[1] ? list[1].split('%%')[0] : data.floorId
    }).then(() => {
      const { image } = this.props;

      if (!image) {
        message.info('暂无平面图');
        return;
      }

      this.setState({ show: true })
    })
  }

  handleSubmit = (e) => {
    e.preventDefault();

    const { dispatch, form, data } = this.props;
    form.validateFields((err: undefined | {}, values: any) => {
      console.log(values)
      if (!err) {
        const res = FOMMATER.map(v => fomatter(
          values[v.list],
          data ? v.names.map(u => data[u]) : null,
          v.len,
          v.names
        ))

        const flag = FOMMATER.every(v => !!v);
        if (!flag) {
          notification['error']({
            message: `保存失败`,
            description: '信息录入不规范',
          });
          return;
        }

        let params = {
          // floorPlanX: values.location ? values.location.split(',')[0] : data ? data.floorPlanX : null,
          // floorPlanY: values.location ? values.location.split(',')[1] : data ? data.floorPlanY : null,
          ...values
        };

        res.forEach(v => {
          params = {
            ...v,
            ...params,
          }
        })

        delete params.systemNo

        data && data.id ? dispatch({
          type: 'device_general/update',
          payload: {
            id: data.id,
            ...params
          },
        }) : dispatch({
          type: 'device_general/create',
          payload: params
        })

      } else {
        notification['error']({
          message: `保存失败`,
          description: '信息录入不规范',
        });
      }
    })
  };

  loadData = (type, selectedOptions) => {

    const { dispatch } = this.props;
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;
    dispatch({
      type: `device_general/${type}`,
      payload: {
        target: {
          id: targetOption.value.split('%%')[0],
          ind: targetOption.value.split('%%')[1],
        },
        option: selectedOptions.map(v => (v.value.split('%%')[1]))
      }
    })
  };

  render() {
    const { form, data, dict = {} } = this.props;
    // const { getFieldDecorator, getFieldValue } = form;
    const { getFieldDecorator } = form;

    const formItemLayout = {
      labelCol: {
        xs: { span: 12 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 6 },
        sm: { span: 14 },
      },
    };

    const noItemLayout = {
      wrapperCol: { span: 14, offset: 6 },
    };

    const Info = DividerItem(data && data.id ? 'form' : 'plus', '水浸设备')

    return (
      <Form onSubmit={this.handleSubmit}>
        <Info />
        <Row style={{ minHeight: '75vh' }}>
          <Col span={12}>
            {/* {
              data && data.id && <Form.Item
                {...formItemLayout}
                label="系统编号"
              >
                {getFieldDecorator('systemNo', {
                  rules: [{
                    required: true, message: '请输入系统编号',
                  }],
                })(
                  <TrimInput placeholder='请输入系统编号' disabled />
                )}
              </Form.Item>
            } */}
            <Form.Item
              {...formItemLayout}
              label="设备名称"
            >
              {getFieldDecorator('name', {
                rules: [{
                  required: true, message: '请输入设备名称',
                }],
              })(
                <TrimInput placeholder='请输入设备名称' />
              )}
            </Form.Item>
            <Form.Item
              {...formItemLayout}
              label='安装地址'
              required
            >
              {getFieldDecorator('buildList')(
                <Cascader
                  // disabled={!!(data && data.id)}
                  options={this.props.location}
                  loadData={this.loadData.bind(this, 'queryLocation')}
                  changeOnSelect={this.props.lLocation}
                  placeholder={data ? `${data.buildName || ''}${data.floorName || ''}${data.areaName || ''}` : '请选择'}
                />
              )}
            </Form.Item>
            <Form.Item
              {...noItemLayout}
            >
              {getFieldDecorator('installationAddr', {
                rules: [{ required: true, message: '请输入详细地址' }],
              })(
                <TextArea rows={4} style={{ width: '100%', marginTop: '-15px' }} />
              )}
            </Form.Item>
            {/* <Form.Item
              {...formItemLayout}
              label='检查类型'
            >
              {getFieldDecorator('fire', {
                rules: [{ required: true, message: '检查类型' }],
              })(
                (DropDownSelectObj({ dict, type: 'device.fire', disabled: true, onChange: () => { } }))
              )}
            </Form.Item> */}

          </Col>
          <Col span={12}>
            <Form.Item
              {...formItemLayout}
              label="IMEI码"
            >
              {getFieldDecorator('networkAddr', {
                rules: [{
                  required: true, message: '请输入IMEI码',
                }],
              })(
                <TrimInput placeholder='请输入IMEI码' />
              )}
            </Form.Item>
            <Form.Item
              {...formItemLayout}
              label="设备编号"
            >
              {getFieldDecorator('serialNumber')(
                <TrimInput placeholder='请输入S/N码' />
              )}
            </Form.Item>
            <Form.Item
              {...formItemLayout}
              label='设备注册号'
            >
              {getFieldDecorator('cardNo', {
                rules: [{ message: '请输入卡号', }],
              })(
                <TrimInput placeholder='请输入卡号' />
              )}
            </Form.Item>
            <Form.Item
              {...formItemLayout}
              label='厂家型号'
              // required
            >
              {getFieldDecorator('brandList')(
                <Cascader
                  options={this.props.brand}
                  loadData={this.loadData.bind(this, 'queryBrand')}
                  changeOnSelect={this.props.lBrand}
                  placeholder={data ? `${data.brandName || ''}${data.productName || ''}` : '请选择'}
                />
              )}
            </Form.Item>
            {/* <Form.Item
              {...formItemLayout}
              label='平面图坐标'
            >
              {getFieldDecorator('location')(
                <MyButton onClick={this.handleMap}>
                  <MyIcon icon="environment" />选择坐标
                </MyButton>
              )}
              <span>{getFieldValue('location')}</span>
            </Form.Item> */}
          </Col>
        </Row>
        <Button style={{ marginLeft: 20 }} onClick={() => {
          window.history.back()
        }}>取消</Button>
        <Button
          type="primary"
          htmlType="submit"
          style={{ marginLeft: 20 }}
        >保存</Button>
        {/* <Modal
          visible={this.state.show}
          title="平面图坐标"
          width={960}
          okText="保存"
          destroyOnClose={true}
          onCancel={() => this.setState({ show: false, tmpLocation: null })}
          onOk={() => {
            form.setFieldsValue({
              location: this.state.tmpLocation
                ? this.state.tmpLocation.join(',')
                : (data && data.floorPlanX ? `${data.floorPlanX},${data.floorPlanY}` : '')
              })
            this.setState({ show: false, tmpLocation: null })
          }}
        >
          <PointSelect
            image={this.props.image}
            location={getFieldValue('location') ? getFieldValue('location').split(',') : []}
            setPoint={v => this.setState({ tmpLocation: v })}
          />
        </Modal> */}
      </Form >
    );
  }
}

const FormList = Form.create<Props>()(FormItem);
export default FormList;

const FOMMATER = [{
  names: ['buildId', 'floorId', 'areaId'],
  list: 'buildList',
  len: 2
}]
